package com.jin.webvideo.base.spring.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

public class InterceptorChain implements HandlerInterceptor {
    List<InterceptorChainItem> interceptors = new ArrayList<>(0);

    public void add(InterceptorChainItem interceptorChainItem) {
        interceptors.add(interceptorChainItem);
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        for (InterceptorChainItem interceptor : interceptors) {
            if (!interceptor.preHandle(request, response, handler)) {
                return false;
            }
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        for (int i = interceptors.size() - 1; i >= 0; i--) {
            InterceptorChainItem interceptor = interceptors.get(i);
            interceptor.postHandle(request, response, handler, modelAndView);
        }
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
}
